import { defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import { PrimeVueResolver } from 'unplugin-vue-components/resolvers';
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons';
import { resolve } from 'path';

export default ({ mode }) =>
  defineConfig({
    plugins: [
      vue(),
      AutoImport({
        resolvers: [],
        include: [
          /\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
          /\.vue$/,
          /\.vue\?vue/ // .vue
        ],
        imports: ['vue', 'vue-router', '@vueuse/core', 'pinia'],
        dts: 'typings/auto-imports.d.ts',
        dirs: ['./src/request/**', './src/utils/**', './src/store/**'],
        vueTemplate: true
      }),
      Components({
        dirs: ['src/components'],
        dts: true,
        deep: true,
        resolvers: [PrimeVueResolver()]
      }),
      createSvgIconsPlugin({
        iconDirs: [resolve(process.cwd(), 'src/assets/icons')],
        symbolId: 'icon-[name]'
      })
    ],
    resolve: {
      alias: [
        // { find: '@vue-office', replacement: resolve(__dirname, 'node_modules/@vue-office') },
        { find: '@', replacement: resolve(__dirname, 'src') }
      ]
    },
    server: {
      port: 8990,
      proxy: {
        '/api': {
          target: loadEnv(mode, process.cwd()).VITE_BASE_URL,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '')
        }
      }
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: '@import "./src/styles/colors.scss";'
        }
      }
    },
    // 配置打包文件输出
    build: {
      outDir: 'cloud',
      // 压缩配置
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true
        }
      },
      rollupOptions: {
        output: {
          entryFileNames: 'js/[name].[hash].js',
          chunkFileNames: 'js/[name].[hash].js',
          assetFileNames(assetInfo) {
            if (assetInfo.name.endsWith('.css')) {
              return 'css/[name].[hash].css';
            }
            if (
              ['.png', '.jpg', '.jpeg', '.svg'].some((ext) =>
                assetInfo.name.endsWith(ext)
              )
            ) {
              return 'imgs/[name].[hash].[ext]';
            }
            return 'assets/[name].[hash].[ext]';
          }
        }
      }
    }
  });
